package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tanhua.server.mapper.UserMapper;
import com.tanhua.server.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


import java.time.Duration;
import java.util.Map;

@Service
public class FreezeService {
    @Autowired
    private UserMapper freezeMapper;
    @Autowired
    private RedisTemplate<String,String>redisTemplate;
    public String queryFreeze(Map<String, Object> param) {
        //todo 校验token
        //获取参数
           Integer userId= (Integer) param.get("userId");
           Integer freezingRange= Integer.parseInt(param.get("freezingRange").toString());
           Integer freezingTime=Integer.parseInt(param.get("freezingTime").toString());
           String reasonsForFreezing=((String) param.get("reasonsForFreezing"));
           String frozenRemarks=((String) param.get("frozenRemarks"));
           //判断冻结状态及时间是否一致
        QueryWrapper<User>wrapper=new QueryWrapper<>();
        wrapper.eq("freezingRange",freezingRange).eq("freezingTime",freezingTime).eq("id",userId);
        User freeze=  freezeMapper.selectOne(wrapper);
        if (freeze!=null){
            return null;
        }
        //修改参数
        UpdateWrapper<User>updateWrapper=new UpdateWrapper<>();
        updateWrapper.set("freezingRange",freezingRange).set("freezingTime",freezingTime).set("reasonsForFreezing",reasonsForFreezing)
                .set("frozenRemarks",frozenRemarks).eq("id",userId);
        freezeMapper.update(freeze,updateWrapper);
        //设置redisKey
         String redisKey="FREEZEUPDATE"+userId;
        Long day=0L;
        switch (freezingTime){
            case 1:{
                day=3L;
                break;
            }
            case 2:{
                day=7L;
                break;
            }
            case 3:{
                day=10000L;
                break;
            }
        }
        redisTemplate.opsForValue().set(redisKey,"1", Duration.ofDays(day));
        return "冻结成功";
    }

    public String queryUnFreeze(Integer userId,String reasonsForThawing) {
        //根据userId查询用户
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("id",userId);
        User freeze= freezeMapper.selectOne(wrapper);
        //判断用户冻结状态 定义0为未冻结
        if (freeze.getFreezingRange()==0){
         return null;
        }
        //修改用户状态
        UpdateWrapper<User>updateWrapper=new UpdateWrapper<>();
        updateWrapper.set("freezingRange",0).set("freezingTime",0).set("reasonsForThawing",reasonsForThawing).eq("id",userId);
        freezeMapper.update(freeze,updateWrapper);
        String redisKey="FREEZEUPDATE"+userId;
        redisTemplate.delete(redisKey);
        return "解冻成功";
    }
}
